package com.lyf.shop.services.Impl;

import com.lyf.shop.dao.CartDao;
import com.lyf.shop.dao.Impl.CartDaoImpl;
import com.lyf.shop.entity.Cart;
import com.lyf.shop.entity.Product;
import com.lyf.shop.services.CartService;
import com.lyf.shop.services.ProductService;

import java.sql.SQLException;
import java.util.List;

public class CartServiceImpl implements CartService {
    private CartDao cartDao = new CartDaoImpl();
    @Override
    public void operation(int uid, int pid) {
        //查询数据 然后判断用户的购物车中是否已有该商品的数据存在
        try {
            Cart cart = cartDao.findCart(uid, pid);
            //判断购物车是否为空
            if(cart!=null){
                //购物车已经有该数据存在
                //修改
                //先设置商品数量
                cart.setCnum(cart.getCnum()+1);
                //再设置商品小计
                cart.setCcount(cart.getProduct().getPprice()*cart.getCnum());
                //修改元数据，数量加一 即小计重新计算为（数量*单价）
                cartDao.updateCart(cart);
            }else {
                cart = new Cart();
                //使用pid来查询对应的商品，用户保存我们的购物车信息
                //调用product中的事务层
                ProductService productService = new ProductServiceImpl();
                //在product中获取pid
                Product product = productService.getProById(pid);
                //新加入购物车的商品数量起始为1
                cart.setCnum(1);
                cart.setProduct(product);
                //商品数量单价计算小计
                cart.setCcount(cart.getCnum()*product.getPprice());
                cart.setUid(uid);
                cartDao.addCart(cart);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    public List<Cart> findCart(int uid) {
        try {
            if (uid>0){
                return cartDao.findCart(uid);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public int delCart(int uid, int pid) {
        try {
            if(pid==0){
                //pid=0时清空购物车
                cartDao.delCart(uid);
            }else {
                //否则删除单个购物车数据
                cartDao.delCart(uid,pid);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    @Override
    public int updateCart(Cart cart) {
        try {
            if(cart!=null){
                return cartDao.updateCart(cart);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    @Override
    public Cart findCart(int uid, int pid) {
        try {
            return cartDao.findCart(uid,pid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
}
